/**
 * CopyRight zh
 * 2018/08/18
 * watermark.js
 * version : 1.0.0
 */
'use strict'
/**
 * 引用: import * as ImgCompress from '@/utils/canvas/compress'
 * demo: <input class="upload-item-input" type="file"  accept="image/*" name="file" @change="PreviewImage(e)"/>
 * 使用示例: const newFile = e.target.files[0]
 ImgCompress.photoCompress(newFile, { quality: 0.5 }, function(base64Codes) {
    // console.log('callback-base64Codes', base64Codes)
    const blob = ImgCompress.convertBase64UrlToBlob(base64Codes)
    const { lastModified, type } = newFile
    const compress_file = new File([blob], imgName, { type: type, lastModified: lastModified })
    // this.tempImage[that.currentImage] = base64Codes
    // this.unpload(compress_file, imgName)
  })
 * @param file imgFile
 * @param w { quality: 0.5 } 压缩比例/清晰度
 * @param callback 回调返回 base64Codes图片的base64地址
 **/
export function photoCompress(file, w, objDiv) {
  var ready = new FileReader()
  /* 开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
  ready.readAsDataURL(file) // 调用reader.readAsDataURL()方法，把图片转成base64
  ready.onload = function() {
    var re = this.result
    canvasDataURL(re, w, objDiv)
  }
}

function canvasDataURL(path, obj, callback) {
  console.log('obj', obj)
  var img = new Image()
  img.src = path
  img.onload = function() {
    var that = this
    // 默认按比例压缩
    let w = that.width
    let h = that.height
    const scale = w / h
    w = obj.width || w
    h = obj.height || (w / scale)
    var quality = 0.6 // 默认图片质量为0.7
    // 生成canvas
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    // 创建属性节点
    var anw = document.createAttribute('width')
    anw.nodeValue = w
    var anh = document.createAttribute('height')
    anh.nodeValue = h
    canvas.setAttributeNode(anw)
    canvas.setAttributeNode(anh)
    ctx.drawImage(that, 0, 0, w, h)
    // 图像质量
    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
      quality = obj.quality
    }
    // quality值越小，所绘制出的图像越模糊
    var base64 = canvas.toDataURL('image/jpeg', quality)
    // 回调函数返回base64的值
    // console.log('base64', base64)
    callback(base64)
  }
}
/**
* 将以base64的图片url数据转换为Blob
* @param urlData
* 用url方式表示的base64图片数据
*/
export function convertBase64UrlToBlob(urlData) {
  const arr = urlData.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

